package com.qilu.pe.ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.ActivityUtils;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qilu.pe.R;
import com.qilu.pe.base.Base2Activity;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.base.Global;
import com.qilu.pe.base.MyApp;
import com.qilu.pe.base.PayResult;
import com.qilu.pe.dao.bean.Doctor;
import com.qilu.pe.dao.bean.ItemSet;
import com.qilu.pe.dao.bean.OrderSuccessInfo;
import com.qilu.pe.dao.bean.Patient;
import com.qilu.pe.dao.bean.PostCouponData;
import com.qilu.pe.dao.bean.ProportionData;
import com.qilu.pe.dao.bean.RefreshEvent;
import com.qilu.pe.dao.bean.ReportDetail;
import com.qilu.pe.dao.bean.SampleAndConsume;
import com.qilu.pe.dao.bean.SettingsData;
import com.qilu.pe.dao.bean.UPayInfo;
import com.qilu.pe.dao.bean.WxPayInfo;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.ActiviceCollector;
import com.qilu.pe.support.util.AlertUtil;
import com.qilu.pe.support.util.GlideUtil;
import com.qilu.pe.support.util.Logg;
import com.qilu.pe.support.util.ReqUtil;
import com.qilu.pe.support.util.ViewUtil;
import com.qilu.pe.ui.adapter.ProjectItemListAdapter;
import com.qilu.pe.ui.adapter.SetItemListAdapter;
import com.qilu.pe.ui.adapter.SetCardHolder;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.ToastUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;
import com.unionpay.uppay.PayActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 确认预约信息
public class ConfirmPlaceOrderInfoActivity extends Base2Activity {
    private TextView tv_name, tv_age, tv_sex, tv_phone, tv_time;// 患者姓名
    private TextView tv_test_price, tv_discount, tv_freight, tv_coupon, tv_item_total;// 支付信息
    private TextView tv_price, vDiscountTitle, vDiscount, vFreePostHint, vPostFee, vPostCoupon;// 总结,检验费,支付信息合计
    private CardView cv_item;// 慢性病套餐,检测项目
    private RecyclerView rcv_item, rcv_sample_consemu;// 项目列表,套餐列表,样本耗材列表
    private TextView tv_ok, tv_sample_date, tv_sample_time;// 确认支付 采样日期 采样时间
    private TextView tv_sample_time0;
    private AppCompatEditText et_clinic_diag, et_remark;// 临床诊断,备注
    private LinearLayout vSetContainer;

    private ProjectItemListAdapter itemAdapter;

    private Patient patient;// 预约传过来的患者对象
    private String orderTime;// 预约传过来的预约时间
    private List<ItemSet> itemList = new ArrayList<>();// 预约传过来的项目
    private List<SetCardHolder> mSetCards = new ArrayList<>();
    private List<ItemSet> itemInSetList = new ArrayList<>();// 根据套餐请求其中包含的项目(用于获取套餐的耗材信息)
    private boolean isItemInSetOk = false;// 获取套餐下的项目列表完成

    private List<ItemSet> setList = new ArrayList<>();

    private List<SampleAndConsume> sampleAndConsumeList = new ArrayList<>();// 项目样本和耗材列表
    private StringBuffer subIdJsonArr;// 项目subId的数组
    private SampleAndConsumeListAdapter sampleAndConsumeAdapter;

    private OrderSuccessInfo orderSuccessInfo;// 预约成功的单号

    private boolean submitOrderSuccess=false;//提交订单成功--防止重复下单

    IWXAPI msgApi;

    // 下单需要的数据
    String mCombo = "";// 套餐数据 数组
    String mProject = "";// 项目数据(数组)
    String mSubmenu = "";// 分单数据(数组)
    String mCount = "";// 耗材总数
    String mSid = "";// 患者id
    String mSamp_date = "";// 采样日期
    String mSamp_time = "";// 采样时间
    String mMoney = "";// 原价
    String mPrice = "";// 实付价格
    String mTime = "";// 预约日期 格式:2020-09-04
    String mFreight = "0";//运费
    String mRemark = "";// 备注
    String mDiagnose = "";// 临床诊断
    String mDiscount = "0";// 优惠折扣

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_confirm_place_order_info;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActiviceCollector.addActivity(this);
        tv_name = findViewById(R.id.tv_name);
        tv_name.setOnClickListener(this);
        tv_age = findViewById(R.id.tv_age);
        tv_sex = findViewById(R.id.tv_sex);
        tv_phone = findViewById(R.id.tv_phone);
        tv_time = findViewById(R.id.tv_time);
        cv_item = findViewById(R.id.cv_item);
        rcv_item = findViewById(R.id.rcv_item);
        rcv_sample_consemu = findViewById(R.id.rcv_sample_consemu);
        tv_test_price = findViewById(R.id.tv_test_price);
        tv_discount = findViewById(R.id.tv_discount);
        tv_freight = findViewById(R.id.tv_freight);
        tv_coupon = findViewById(R.id.tv_coupon);
        tv_price = findViewById(R.id.tv_price);
        tv_item_total = findViewById(R.id.tv_item_total);
        tv_sample_time = findViewById(R.id.tv_sample_time);
        tv_sample_date = findViewById(R.id.tv_sample_date);
        tv_ok = findViewById(R.id.tv_ok);
        tv_sample_time0 = findViewById(R.id.tv_sample_time0);
        et_clinic_diag = findViewById(R.id.et_clinic_diag);
        et_remark = findViewById(R.id.et_remark);
        vDiscountTitle = findViewById(R.id.vDiscountTitle);
        vDiscount = findViewById(R.id.vDiscount);
        vSetContainer = findViewById(R.id.vSetContainer);
        vFreePostHint = findViewById(R.id.vFreePostHint);
        vPostFee = findViewById(R.id.vPostFee);
        vPostCoupon = findViewById(R.id.vPostCoupon);

        ViewUtil.setImportantText(tv_sample_time0, "*采样时间");
        setHeadTitle("确认预约信息");

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            patient = (Patient) bundle.getSerializable("patient");
            orderTime = bundle.getString("orderTime");
            itemList = (List<ItemSet>) bundle.getSerializable("itemList");
            setList = (List<ItemSet>) bundle.getSerializable("setList");
            mTime = bundle.getString("time");
        }

        if (setList.size() > 0) {// 有套餐,先获取套餐其下的项目,再获取所有项目下的耗材信息
            for (int i = 0; i < setList.size(); i++) {
                addSetCardToLayout(setList.get(i));
                reqItemInSetList(setList.get(i).getId(), i);// 根据套餐获取其下的项目
            }
        } else {// 没有套餐,直接请求项目下的耗材信息
            reqSampleAndConsumeList();
        }

        alert = new AlertDialog.Builder(this, R.style.Dialog_FS).create();
        alert2 = new AlertDialog.Builder(this, R.style.Dialog_FS).create();

        setListeners();
        setViewInfo();
        genSubIdData();
        showProgress();

        msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(Config.WX_APP_ID);
        EventBus.getDefault().register(this);
    }

    public void addSetCardToLayout(ItemSet set) {
        View v = LayoutInflater.from(this).inflate(R.layout.item_set_card, null, false);
        SetCardHolder holder = new SetCardHolder(this);
        holder.setItem(v, set);
        mSetCards.add(holder);
        vSetContainer.addView(v);
    }

    private void setListeners() {
        setOnClickListener(tv_ok, tv_sample_date, tv_sample_time);

        alert.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                // 未支付返回提示信息：您的订单未支付，请尽快完成支付。
                // 继续支付按钮/确认离开按钮，点击确认离开跳转到我的订单列表页
                showDialog2();
            }
        });
    }

    private AlertDialog alert2;// 弹窗
    private View alert_view2;

    public void showDialog2() {// 弹窗
        alert2.show();
        alert_view2 = View.inflate(this, R.layout.layout_alert_com_alert, null);

        TextView tv_1 = alert_view2.findViewById(R.id.tv_1);
        TextView tv_2 = alert_view2.findViewById(R.id.tv_2);
        TextView tv_title = alert_view2.findViewById(R.id.tv_title);
        tv_1.setText("继续支付");
        tv_2.setText("确认离开");
        tv_title.setText("您的订单未支付，请尽快完成支付。");
        tv_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert2.dismiss();
                showDialog();
            }
        });
        tv_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert2.dismiss();
                startActivity(MyOrderActivity.class);
                ActivityUtils.finishActivity(PlaceOrderActivity.class);
                finish();
            }
        });

        AlertUtil.setAlertCenterStyle(alert2.getWindow(), alert_view2, this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_ok) {// 提交订单
            if (mSamp_time.isEmpty()) {
                ToastUtils.showShort("请选择采样时间");
            } else {
                if(submitOrderSuccess){
                    showDialog();
                }else{
                    reqSubmitPlaceOrder();
                    reqUserInfo();
                }

            }
        }
        if (v == tv_sample_date) {// 点击选择采样日期
            sample_type = 1;
            initDatePicker();
            pvTime.show();
        }
        if (v == tv_sample_time) {// 点击选择采样时间
            sample_type = 2;
            initTimePicker();
            pvTime.show();
        }
        if (v == tv_name) {
            Bundle bundle = new Bundle();
            bundle.putSerializable("patient", patient);
            startActivity(PatientDetailActivity.class, bundle);
        }
    }

    private TimePickerView pvTime;
    private int sample_type = 1;// 时间选择器的类型 1 日期 2 时间

    private void initTimePicker() {//Dialog 模式下，在底部弹出
        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                mSamp_time = getTime(date);
                tv_sample_time.setText(mSamp_time);
            }
        }).setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
            @Override
            public void onTimeSelectChanged(Date date) {
            }
        }).setType(new boolean[]{false, false, false, true, true, true})
                .isDialog(true) // 默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                })
                .setItemVisibleCount(7) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .isAlphaGradient(true)
                .setTitleText("选择时间")
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }

    private void initDatePicker() {//Dialog 模式下，在底部弹出
        // 注意月份 0-11代表1-12月份
//        int year = Calendar.getInstance().get(Calendar.YEAR);
//        int sMonth = Calendar.getInstance().get(Calendar.MONTH);
//        int sDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
        Calendar startDate = Calendar.getInstance();
//        startDate.set(year, sMonth, sDay);

        Date orderDate = new Date();
        try {
            orderDate = new SimpleDateFormat(Config.TIME_FORMATE).parse(mTime + " 23:59:59");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar endDate = Calendar.getInstance();
        endDate.setTime(orderDate);
        final Calendar finalDate = endDate;

        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                mSamp_date = getTime(date);
                tv_sample_date.setText(mSamp_date);
            }
        }).setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
            @Override
            public void onTimeSelectChanged(Date date) {
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .isDialog(true) // 默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                })
                .setItemVisibleCount(7) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .isAlphaGradient(true)
                .setTitleText("选择日期")
                .setRangDate(startDate, finalDate)
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (sample_type == 1) {// 采样日期
            SimpleDateFormat format = new SimpleDateFormat(Config.TIME_FORMATE_YMD);
            return format.format(date);
        } else {// 采样时间
            SimpleDateFormat format = new SimpleDateFormat(Config.TIME_FORMATE_HMS);
            return format.format(date);
        }
    }

    private void setViewInfo() {
        if (null != patient) {
            tv_name.setText(patient.getName());
            tv_age.setText(String.valueOf(patient.getAge()));
            tv_sex.setText(TextUtils.equals("1", patient.getSex()) ? "女" : "男");
            tv_phone.setText(patient.getPhone());

            mSid = patient.getId();// 患者id
        }
        tv_time.setText(orderTime);

        // 采样时间
        mSamp_date = mTime;
        mSamp_time = "";
        tv_sample_date.setText(mTime);
        tv_sample_time.setText("");

        itemAdapter = new ProjectItemListAdapter(this);

        LinearLayoutManager manager2 = new LinearLayoutManager(this);
        sampleAndConsumeAdapter = new SampleAndConsumeListAdapter(this);
        rcv_sample_consemu.setLayoutManager(manager2);
        rcv_sample_consemu.setAdapter(sampleAndConsumeAdapter);

        if (setList.size() <= 0) {
//            cv_set.setVisibility(View.GONE);
        } else {
//            cv_set.setVisibility(View.VISIBLE);
//            LinearLayoutManager manager = new LinearLayoutManager(this);
//            rcv_set.setLayoutManager(manager);
//            rcv_set.setAdapter(setAdapter);
        }
        if (itemList.size() <= 0) {
            cv_item.setVisibility(View.GONE);
        } else {
            cv_item.setVisibility(View.VISIBLE);
            LinearLayoutManager manager = new LinearLayoutManager(this);
            rcv_item.setLayoutManager(manager);
            rcv_item.setAdapter(itemAdapter);
        }
        setSelectedItemListAndPrice();
    }

    private void setSelectedItemListAndPrice() {
        itemAdapter.setDataList(itemList);

        mMoney = getItemSetTotalPrice();// 原价
        tv_test_price.setText("¥" + mMoney);
        tv_item_total.setText("¥" + mMoney);
        tv_price.setText("总价：¥" + mMoney);

        //获取机构折扣
        APIRetrofit.getDefault().getProportion(Global.HEADER)
                .compose(RxUtil.<BaseResult2<List<ProportionData>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<ProportionData>>>() {
                    @Override
                    public void accept(BaseResult2<List<ProportionData>> res) throws Exception {
                        if (res.isSuccess()) {
                            final BigDecimal total = new BigDecimal(mMoney);
                            BigDecimal discountRate = new BigDecimal(res.getData().get(0).getProportion());
                            vDiscountTitle.setText(String.format("折扣优惠(%1$s折):", discountRate.toString()));
                            final BigDecimal discount = total.subtract(total.multiply(discountRate).divide(new BigDecimal(10)));
                            vDiscount.setText("-￥" + discount.toString());
                            mDiscount = discount.toString();
                            //获取运费、免运费标准
                            APIRetrofit.getDefault().getSettings(Global.HEADER)
                                    .compose(RxUtil.<BaseResult2<List<SettingsData>>>subIoObMain())
                                    .subscribe(new Consumer<BaseResult2<List<SettingsData>>>() {
                                        @Override
                                        public void accept(BaseResult2<List<SettingsData>> result) throws Exception {
                                            if (result.isSuccess()) {
                                                final SettingsData settings = result.getData().get(0);
                                                vFreePostHint.setText(String.format("检验费>=%1$s免邮", settings.getFree()));
                                                final BigDecimal realPay = total.subtract(discount);
                                                //实付金额不满足免运费标准
                                                if (total.compareTo(new BigDecimal(settings.getFree())) < 0) {
                                                    vPostFee.setText("￥" + settings.getFreight());
                                                    //查询运费券
                                                    APIRetrofit.getDefault().getPostCoupon(Global.HEADER, mTime)
                                                            .compose(RxUtil.<BaseResult2<List<PostCouponData>>>subIoObMain())
                                                            .subscribe(new Consumer<BaseResult2<List<PostCouponData>>>() {
                                                                @Override
                                                                public void accept(BaseResult2<List<PostCouponData>> postCouponRes) throws Exception {
                                                                    if (postCouponRes.isSuccess()) {
                                                                        List<PostCouponData> couponList = postCouponRes.getData();
                                                                        if (couponList != null && couponList.size() > 0) {
                                                                            PostCouponData coupon = null;
                                                                            for (PostCouponData c : couponList) {
                                                                                if (c.getType() == 0) {
                                                                                    coupon = c;
                                                                                    break;
                                                                                }
                                                                            }
                                                                            if (coupon != null) {
                                                                                //有可用优惠券
                                                                                vPostCoupon.setText("￥" + coupon.getPrice());
                                                                                BigDecimal payPostFee = new BigDecimal(settings.getFreight()).subtract(coupon.getPrice());
                                                                                mFreight = payPostFee.toString();
                                                                                //计算合计
                                                                                BigDecimal pay = realPay.add(payPostFee);
                                                                                mPrice = pay.toString();
                                                                                tv_item_total.setText("¥" + mPrice);
                                                                                tv_price.setText("总价：¥" + mPrice);
                                                                            } else {
                                                                                //没有可用优惠券，计算合计
                                                                                BigDecimal payPostFee = new BigDecimal(settings.getFreight());
                                                                                mFreight = payPostFee.toString();
                                                                                BigDecimal pay = realPay.add(payPostFee);
                                                                                mPrice = pay.toString();
                                                                                tv_item_total.setText("¥" + mPrice);
                                                                                tv_price.setText("总价：¥" + mPrice);
                                                                            }
                                                                        } else {
                                                                            //没有优惠券，计算合计
                                                                            BigDecimal payPostFee = new BigDecimal(settings.getFreight());
                                                                            mFreight = payPostFee.toString();
                                                                            BigDecimal pay = realPay.add(payPostFee);
                                                                            mPrice = pay.toString();
                                                                            tv_item_total.setText("¥" + mPrice);
                                                                            tv_price.setText("总价：¥" + mPrice);
                                                                        }
                                                                    } else {
                                                                        ToastUtils.showShort(postCouponRes.getMsg());
                                                                        //接口异常，直接计算合计
                                                                        BigDecimal payPostFee = new BigDecimal(settings.getFreight());
                                                                        mFreight = payPostFee.toString();
                                                                        BigDecimal pay = realPay.add(payPostFee);
                                                                        mPrice = pay.toString();
                                                                        tv_item_total.setText("¥" + mPrice);
                                                                        tv_price.setText("总价：¥" + mPrice);
                                                                    }
                                                                }
                                                            }, new Consumer<Throwable>() {
                                                                @Override
                                                                public void accept(Throwable throwable) throws Exception {
                                                                    throwable.printStackTrace();
                                                                }
                                                            });
                                                } else {
                                                    //计算合计
                                                    mPrice = realPay.toString();
                                                    tv_item_total.setText("¥" + mPrice);
                                                    tv_price.setText("总价：¥" + mPrice);
                                                }
                                            } else {
                                                ToastUtils.showShort(result.getMsg());
                                            }
                                        }
                                    }, new Consumer<Throwable>() {
                                        @Override
                                        public void accept(Throwable throwable) throws Exception {
                                            throwable.printStackTrace();
                                        }
                                    });
                        } else {
                            ToastUtils.showShort(res.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
    }

    // 计算套餐总价格
    private String getItemSetTotalPrice() {
        BigDecimal total = new BigDecimal(0);
        if (itemList.size() <= 0 && setList.size() <= 0) {
            return total.doubleValue() + "";
        }
        for (int i = 0; i < itemList.size(); i++) {
            double temp = Double.parseDouble(itemList.get(i).getPrice());
            total = total.add(new BigDecimal(temp));
        }
        for (int i = 0; i < setList.size(); i++) {
            double temp = Double.parseDouble(setList.get(i).getPrice());
            total = total.add(new BigDecimal(temp));
        }
        return total.doubleValue() + "";
    }

    // 这个方法可能没用
    private void genSubIdData() {
        if (itemList.size() >= 1) {
            subIdJsonArr = new StringBuffer("{");
            // 先封装选择的原始项目的耗材信息
            for (int i = 0; i < itemList.size(); i++) {
                if (i < itemList.size() - 1) {
                    subIdJsonArr.append(itemList.get(i).getSub_id() + ",");
                } else {
                    subIdJsonArr.append(itemList.get(i).getSub_id());
                }
            }
            // 再封装选择的套餐其下的项目的耗材信息
            for (int i = 0; i < itemInSetList.size(); i++) {
                if (i < itemInSetList.size() - 1) {
                    subIdJsonArr.append(itemInSetList.get(i).getSub_id() + ",");
                } else {
                    subIdJsonArr.append(itemInSetList.get(i).getSub_id());
                }
            }
            subIdJsonArr.append("}");
        }
    }

    private Disposable reqItemInSetList(String id, final int i) {
        return APIRetrofit.getDefault().reqItemInSetList(id)
                .compose(RxUtil.<BaseResult2<List<ItemSet>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<ItemSet>>>() {
                    @Override
                    public void accept(BaseResult2<List<ItemSet>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {
                            List<ItemSet> newData = listBaseResult2.getData();
                            mSetCards.get(i).setSetItem(newData);
                            itemInSetList.addAll(newData);
                            if (i == setList.size() - 1) {// 根据套餐请求其下的项目
//                                genSubIdData();
                                isItemInSetOk = true;
                                reqSampleAndConsumeList();
                            }
                        } else {

                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 新增 提交 预约订单
    private Disposable reqSubmitPlaceOrder() {
        // 整合套餐数据
        List<Map<String, String>> comboMapList = new ArrayList<>();
        for (int i = 0; i < setList.size(); i++) {
            Map<String, String> comboMap = new HashMap<>();
            comboMap.put("id", setList.get(i).getId());
            comboMap.put("name", setList.get(i).getName());
            comboMapList.add(comboMap);
        }
        mCombo = ReqUtil.getJsonStr(comboMapList);

        // 整合项目数据
        List<Map<String, String>> projectMapList = new ArrayList<>();
        for (int i = 0; i < itemList.size(); i++) {
            Map<String, String> projectMap = new HashMap<>();
            projectMap.put("id", itemList.get(i).getId());
            projectMap.put("name", itemList.get(i).getName());
            projectMap.put("code", itemList.get(i).getCode());
            projectMap.put("price", itemList.get(i).getPrice());
            projectMap.put("sub_id", itemList.get(i).getSub_id());
            projectMap.put("day", itemList.get(i).getDay());
            projectMapList.add(projectMap);
        }
        mProject = ReqUtil.getJsonStr(projectMapList);

        // 整合分单信息
        List<Map<String, String>> submenuMapList = new ArrayList<>();
        for (int i = 0; i < sampleAndConsumeList.size(); i++) {
            Map<String, String> submenuMap = new HashMap<>();
            submenuMap.put("id", sampleAndConsumeList.get(i).getId());
            submenuMap.put("sampling", sampleAndConsumeList.get(i).getSampling());
            submenuMap.put("capacity", sampleAndConsumeList.get(i).getCapacity());
            submenuMap.put("count", sampleAndConsumeList.get(i).getCount());
            submenuMap.put("sample", sampleAndConsumeList.get(i).getSample());
            submenuMap.put("picture", sampleAndConsumeList.get(i).getPicture());
            submenuMap.put("supplies", sampleAndConsumeList.get(i).getSupplies());
            submenuMap.put("type", sampleAndConsumeList.get(i).getType());
            submenuMapList.add(submenuMap);
        }
        mSubmenu = ReqUtil.getJsonStr(submenuMapList);

        String test = "t";
        Gson gson = new Gson();

        Map<String, String> combo2 = new HashMap<>();
        if (!isDataEmpty(setList)) {
            for (int i = 0; i < setList.size(); i++) {
                combo2.put("combo[" + i + "]", gson.toJson(setList.get(i)));
            }
        }

        Map<String, String> project2 = new HashMap<>();
        if (!isDataEmpty(itemList)) {
            for (int i = 0; i < itemList.size(); i++) {
                project2.put("project[" + i + "]", gson.toJson(itemList.get(i)));
            }
        }

        Map<String, String> submenu2 = new HashMap<>();
        if (!isDataEmpty(sampleAndConsumeList)) {
            for (int i = 0; i < sampleAndConsumeList.size(); i++) {
                submenu2.put("submenu[" + i + "]", gson.toJson(sampleAndConsumeList.get(i)));
            }
        }

        if (!TextUtils.isEmpty(et_clinic_diag.getText().toString().trim())) {
            mDiagnose = et_clinic_diag.getText().toString().trim();
        }
        if (!TextUtils.isEmpty(et_remark.getText().toString().trim())) {
            mRemark = et_remark.getText().toString().trim();
        }

        String sampleDateTime = mSamp_date + " " + mSamp_time;

        hideProgress();
        showProgressWithText(true, "提交中");
        return APIRetrofit.getDefault().reqSubmitPlaceOrder(test, Global.HEADER, mCombo, mProject, mSubmenu
                , mCount, mSid, sampleDateTime, mMoney, mPrice, mTime, mFreight, mRemark, mDiagnose, mDiscount)
                .compose(RxUtil.<BaseResult2<OrderSuccessInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<OrderSuccessInfo>>() {
                    @Override
                    public void accept(BaseResult2<OrderSuccessInfo> baseResult) throws Exception {
                        hideProgress();
//                        List<String> data = baseResult3.getData();
//                        Logg.i("data = " + data.size());
                        if (baseResult.isSuccess()) {
//                            ToastUtils.showShort("订单提交成功,选择支付方式");
                            orderSuccessInfo = baseResult.getData();
                            submitOrderSuccess=true;
                            showDialog();
                        } else {
                            ToastUtils.showShort(baseResult.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("订单提交失败");
                    }
                });
    }

    // 请求样本耗材
    private Disposable reqSampleAndConsumeList() {

        // json请求体参数
//        List<Map<String, String>> mapList = new ArrayList<>();
//        for (int i = 0; i < itemList.size(); i++) {
//            Map<String, String> map = new HashMap<>();
//            map.put("subId", itemList.get(i).getSub_id());
//            mapList.add(map);
//        }
//        RequestBody body = ReqUtil.getBody(mapList, true);

        Map<String, String> submenu = new HashMap<>();
        List<ItemSet> tmpItemList = new ArrayList<>();// 临时变量,记录项目信息(可能包含原本预约的项目和套餐其下的项目)
        if (setList.size() > 0 && itemInSetList.size() > 0) {
            for (ItemSet set : itemInSetList) {
                if (set.getSub_id() != null) {
                    tmpItemList.add(set);
                }
            }
        }
        if (itemList.size() > 0) {
            tmpItemList.addAll(itemList);
        }
        for (int i = 0; i < tmpItemList.size(); i++) {
            submenu.put("subId[" + i + "]", tmpItemList.get(i).getSub_id());
        }
        return APIRetrofit.getDefault().reqSampleAndConsumeList(submenu)
                .compose(RxUtil.<BaseResult2<List<SampleAndConsume>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<SampleAndConsume>>>() {
                    @Override
                    public void accept(BaseResult2<List<SampleAndConsume>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {

                        } else {

                        }
                        sampleAndConsumeList = listBaseResult2.getData();
                        sampleAndConsumeAdapter.setDataList(sampleAndConsumeList);
                        mCount = sampleAndConsumeList.size() + "";// 耗材数量
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private AlertDialog alert;// 弹窗
    private View alert_view;

    public void showDialog() {// 弹窗界面
        alert.show();
        alert_view = View.inflate(this, R.layout.layout_alert_choose_pay_type, null);

        final RadioButton cb_ali = alert_view.findViewById(R.id.cb_ali);
        final RadioButton cb_wx = alert_view.findViewById(R.id.cb_wx);
        final RadioButton cb_union = alert_view.findViewById(R.id.cb_union);
        final RadioButton cb_balance = alert_view.findViewById(R.id.cb_balance);
        final TextView tv_balance0 = alert_view.findViewById(R.id.tv_balance0);// 显示余额数量

        RelativeLayout rl_ali = alert_view.findViewById(R.id.rl_ali);
        RelativeLayout rl_wechat = alert_view.findViewById(R.id.rl_wechat);
        RelativeLayout rl_union_pay = alert_view.findViewById(R.id.rl_union_pay);
        RelativeLayout rl_balance = alert_view.findViewById(R.id.rl_balance);

        tv_balance0.setText("余额支付 (¥" + Global.ORG_BALANCE + ")");

        rl_ali.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(true);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        cb_ali.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(true);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        rl_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(true);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        cb_wx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(true);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        rl_union_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(true);
                cb_balance.setChecked(false);
            }
        });
        cb_union.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(true);
                cb_balance.setChecked(false);
            }
        });
        rl_balance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(true);
            }
        });
        cb_balance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(true);
            }
        });

        alert_view.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cb_ali.isChecked()) {
                    payType = "2";
                } else if (cb_wx.isChecked()) {
                    payType = "1";
                } else if (cb_union.isChecked()) {
                    payType = "3";
                } else if (cb_balance.isChecked()) {
                    payType = "4";
                }
                if (cb_ali.isChecked()) {// 支付宝
                    hideProgress();
                    reqAliPayInfo();
                    showProgress();
                } else if (cb_wx.isChecked()) {// 微信
                    hideProgress();
                    reqWxPayInfo();
                    showProgress();
                } else if (cb_union.isChecked()) {// 银联
                    hideProgress();
                    Logg.e("==银联支付--==");
                    reqUPayPayInfo();
                    showProgress();
                } else if (cb_balance.isChecked()) {
                    hideProgress();
                    Logg.e("==余额支付==");
                    reqBalancePayInfo();
                    showProgress();
                }
                alert.dismiss();
            }
        });

        AlertUtil.setAlertBottomInStyle(alert.getWindow(), alert_view, this);
    }

    String payType = "2";// 支付方式 1 微信,2 支付宝,3 银联支付,4 余额支付

    private Disposable reqBalancePayInfo() {
        if (null == orderSuccessInfo) {
            ToastUtils.showShort("下单错误,请重试");
            return null;
        }
        return APIRetrofit.getDefault().reqPlaceOrderPayBalance(Global.HEADER, orderSuccessInfo.getOrder_num(), payType)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            paySuc();
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.e("pay_data_balance = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqUPayPayInfo() {
        if (null == orderSuccessInfo) {
            ToastUtils.showShort("下单错误,请重试");
            return null;
        }
        return APIRetrofit.getDefault().reqPlaceOrderPayUpay(Global.HEADER, orderSuccessInfo.getOrder_num(), payType)
                .compose(RxUtil.<BaseResult2<UPayInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<UPayInfo>>() {
                    @Override
                    public void accept(BaseResult2<UPayInfo> baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            Logg.e("==银联支付--uPay==" + baseResult2.getData().getTn());
                            uPay(baseResult2.getData().getTn());
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_upay = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqWxPayInfo() {
        if (null == orderSuccessInfo) {
            ToastUtils.showShort("下单错误,请重试");
            return null;
        }
        return APIRetrofit.getDefault().reqPlaceOrderPayWx(Global.HEADER, orderSuccessInfo.getOrder_num(), payType)
                .compose(RxUtil.<BaseResult2<WxPayInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<WxPayInfo>>() {
                    @Override
                    public void accept(BaseResult2<WxPayInfo> baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            wxPay(baseResult2);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_wx = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取微信支付信息错误");
                    }
                });
    }

    private Disposable reqAliPayInfo() {
        if (null == orderSuccessInfo) {
            ToastUtils.showShort("下单错误,请重试");
            showDialog();
            return null;
        }
        return APIRetrofit.getDefault().reqPlaceOrderPayAli(Global.HEADER, orderSuccessInfo.getOrder_num(), payType)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            String orderInfo = (String) baseResult2.getData();
                            aliPay(orderInfo);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                            showDialog();
                        }
                        Logg.i("pay_data_ali = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 调起银联支付
    private void uPay(String tn) {
//        UPPayAssistEx.startPay(Arad.app, null, null, tn, MyApp.unionPayMode);
//        UPPayAssistEx.startPayByJAR(Arad.app, PayActivity.class,null,null,tn, MyApp.unionPayMode);
        Logg.e("==银联支付--订单号==" + tn);
        UPPayAssistEx.startPay(ConfirmPlaceOrderInfoActivity.this, null, null, tn, MyApp.unionPayMode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        String str = data.getExtras().getString("pay_result");
//        ToastUtils.showShort("银联支付"+str);
        Logg.e("==银联支付--回调==" + str);
        if (str.equalsIgnoreCase("success")) {
            //显示支付结果
            paySuc();
        } else if (str.equalsIgnoreCase("fail")) {
            ToastUtils.showShort("银联支付失败");
            showDialog();
        } else if (str.equalsIgnoreCase("cancel")) {
            ToastUtils.showShort("您取消了银联支付");
            showDialog();
        }
    }

    // 调起微信支付
    private void wxPay(BaseResult2<WxPayInfo> baseResult2) {
        WxPayInfo wxPayInfo = baseResult2.getData();
        PayReq request = new PayReq();
        request.appId = wxPayInfo.getAppid();
        request.partnerId = wxPayInfo.getPartnerid();
        request.prepayId = wxPayInfo.getPrepayid();
        request.packageValue = "Sign=WXPay";
        request.nonceStr = wxPayInfo.getNoncestr();
        request.timeStamp = wxPayInfo.getTimestamp();
        request.sign = wxPayInfo.getSign();
        msgApi.sendReq(request);
    }

    // 调起支付宝支付
    private void aliPay(final String orderInfo) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(ConfirmPlaceOrderInfoActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = 20100851;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        }).start();
    }

    @SuppressWarnings("all")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            //返回码，标识支付状态，含义如下：9000——订单支付成功 8000——正在处理中 4000——订单支付失败 5000——重复请求 6001——用户中途取消 6002——网络连接出错
            if (msg.what == 20100851) {
                PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                String payStatus = payResult.getResultStatus();
                if (TextUtils.equals(payStatus, "9000")) {// 判断resultStatus 为9000则代表支付成功
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    ToastUtils.showShort("支付成功");
                    paySuc();
                } else if (TextUtils.equals(payStatus, "6001")) {
                    ToastUtils.showShort("取消支付");
                    showDialog();
                } else {
                    // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    ToastUtils.showShort("支付失败");
                    showDialog();
                }
            }
        }
    };

    private void paySuc() {
//        startActivity(PaySuccessActivity.class);
//        ActivityUtils.finishActivity(PlaceOrderActivity.class);
//        finish();
        Intent intent=new Intent(ConfirmPlaceOrderInfoActivity.this, PaySuccessActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("from", "ConfirmPlaceOrderInfo");// 标识支付来源-确认预约信息页面
        intent.putExtras(bundle);
        startActivity(intent);
        finish();
//        EventBus.getDefault().post(new RefreshEvent("refreshProductOrderList"));
    }

    private class SampleAndConsumeListAdapter extends ListBaseAdapter<SampleAndConsume> {

        public SampleAndConsumeListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_sample_and_consume_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView tv_consume = holder.getView(R.id.tv_consume);
            TextView tv_num = holder.getView(R.id.tv_num);
            TextView tv_name1 = holder.getView(R.id.tv_name1);
            TextView tv_name2 = holder.getView(R.id.tv_name2);
            TextView tv_name3 = holder.getView(R.id.tv_name3);
            TextView tv_hint = holder.getView(R.id.tv_hint);
            TextView tv_hint_info = holder.getView(R.id.tv_hint_info);
            RoundedImageView iv_sample_img = holder.getView(R.id.iv_sample_img);

            SampleAndConsume consume = mDataList.get(position);

            tv_consume.setText("耗材：" + consume.getSupplies());
            tv_num.setText("×" + consume.getCount());
            tv_name1.setText(consume.getSample());
            tv_name2.setText(TextUtils.equals("1", consume.getType()) ? "常温" : "冷藏");
            tv_name3.setText(consume.getCapacity());
            tv_hint_info.setText(consume.getSampling() == null ? "无" : consume.getSampling());
            GlideUtil.loadImg(Config.URL_IMG + consume.getPicture(), iv_sample_img);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        reqUserInfo();
    }

    // 获取用户信息 此方法在这里刷新用户余额
    private Disposable reqUserInfo() {
        return APIRetrofit.getDefault().getUserInfo(Global.HEADER, "1")
                .compose(RxUtil.<BaseResult2<List<Doctor>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Doctor>>>() {
                    @Override
                    public void accept(BaseResult2<List<Doctor>> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            List<Doctor> doctorList = result2.getData();
                            if (!isDataEmpty(doctorList)) {
                                Doctor doctor = doctorList.get(0);
                                Global.ORG_BALANCE = doctor.getMoney();
                            }
                        } else {

                        }
                        Logg.i("reqUserInfo.result2.getMsg()" + result2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void cancelPay(RefreshEvent e) {
        if (e.getAction() == "cancelPay") {
            showDialog();
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}